//
//  ClassCouresTimeViewController.m
//  HTP
//
//  Created by admin on 15/10/30.
//  Copyright © 2015年 nit. All rights reserved.
//

#import "ClassCouresTimeViewController.h"
#import "ClassCourseDetailViewController.h"
#import "DetailCourseRecordVC.h"
#import "AllCourseClassVC.h"

#import "FSCalendar.h"
#import "CourseCell.h"

#import "AppDelegate.h"

#import "ClassCourseViewModel.h"
#import "ClassCourseTimeModel.h"

#define  CALENDARHEIGHT 200
#define CELLHEIGHT_Course 45
@interface ClassCouresTimeViewController ()<FSCalendarDataSource,FSCalendarDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,retain) FSCalendar *courseCalendar;
@property (nonatomic,retain) NSDate     *selectDate;

@property (nonatomic,strong) BaseTableView *courseTable;

@property (nonatomic,retain) NSArray        *datesArray;

@property (nonatomic,retain) NSArray        *courseClassArray;
@end

@implementation ClassCouresTimeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _courseClassArray = [NSArray array];
    //获取本地数据
    [self.view addSubview:self.courseCalendar];
    [self addWeekendBg];
    [self _initFootView];
    [self.view addSubview:self.courseTable];
    //获取日历记录
    _selectDate = [NSDate date];
    [self getDataForCalendar:[NSDate date]];
    [self getDataForTable:[NSDate date]];
    // Do any additional setup after loading the view.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nsnofiationAction:) name:CHANGECOURSERECORD object:nil];
}
- (void)viewDidUnload{
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self addCustomBackBase];
    [self addCustomTitleWithTitle:@"我的课程"];
    if (_courseClassArray.count != 0) {
        [self.courseTable reloadData];
    }
}
//TODO:绘制UI
/**
 *  底部UI绘制
 yunhe
 */
-(void)_initFootView{
    UIImageView *footImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bottombg"]];
    footImg.userInteractionEnabled = YES;
    [footImg setFrame:CGRectMake(0, ScreenHeihgt - 49 - NavHe, ScreenWidth, 49)];
    [self.view addSubview:footImg];
    [self.view bringSubviewToFront:footImg];
    UIButton *today = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth / 2.0, 49)];
    [today addTarget:self action:@selector(comeToToday) forControlEvents:UIControlEventTouchUpInside];
    [today setTitle:@"今天" forState:UIControlStateNormal];
    [today setTitleColor:RGBCOLOR(250, 153, 54, 0.9) forState:UIControlStateNormal];
    today.titleLabel.font = UIFONTSYS(20);
    today.titleLabel.textAlignment = _TEXT_ALIGN_LEFT;
    today.titleEdgeInsets = UIEdgeInsetsMake(0, -ScreenWidth / 4.0, 5, 0);
    [footImg addSubview:today];
    
    UIButton *all = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth / 2.0, 0, ScreenWidth / 2.0, 49)];
    [all setTitle:@"课程一览" forState:UIControlStateNormal];
    [all setTitleColor:RGBCOLOR(250, 153, 54, 0.9) forState:UIControlStateNormal];
    all.titleLabel.font = UIFONTSYS(20);
    all.titleLabel.textAlignment = _TEXT_ALIGN_RIGHT;
    all.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 5, -ScreenWidth / 4.0+40);
    [all addTarget:self action:@selector(getAllCourseAction) forControlEvents:UIControlEventTouchUpInside];
    [footImg addSubview:all];
}

//TODO:重写get方法
/**
 *  初始化日历
    yunhe
 *
 *  @return FSCalendar
 */
-(FSCalendar *)courseCalendar{
    if (!_courseCalendar) {
        _courseCalendar = [[FSCalendar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, CALENDARHEIGHT)];
        _courseCalendar.dataSource = self;
        _courseCalendar.delegate = self;
        _courseCalendar.today = [NSDate date];
        _courseCalendar.scrollDirection = FSCalendarScrollDirectionVertical;
        _courseCalendar.currentPage = [NSDate date];
        _courseCalendar.allowsMultipleSelection = NO;
        _courseCalendar.backgroundColor = [UIColor clearColor];
        _courseCalendar.headerHeight = 20;
        _courseCalendar.weekdayHeight = 20;
        _courseCalendar.appearance.weekdayTextColor = [UIColor whiteColor];
        _courseCalendar.appearance.headerTitleColor = [UIColor whiteColor];
        _courseCalendar.appearance.eventColor = [UIColor clearColor];
        _courseCalendar.appearance.cellShape =  FSCalendarCellShapeCircle;
        _courseCalendar.appearance.caseOptions = FSCalendarCaseOptionsWeekdayUsesDefaultCase;
        _courseCalendar.appearance.selectionColor = [UIColor blackColor];
        _courseCalendar.appearance.todayColor = [UIColor orangeColor];
    }
    return _courseCalendar;
}
-(void)addWeekendBg{
    UIImageView *backImage = [[UIImageView alloc] init];
    backImage.image = [UIImage imageNamed:@"navBG"];
    [backImage setFrame:CGRectMake(0, 0, ScreenWidth, 40)];
    [self.view addSubview:backImage];
    [self.view sendSubviewToBack:backImage];
    
    UIImageView *back_1 = [[UIImageView alloc] init];
    back_1.image = [UIImage imageNamed:@"courseBackground"];
    [back_1 setFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeihgt)];
    [self.view addSubview:back_1];
    [self.view sendSubviewToBack:back_1];
}
/**
 *  课程tableView
 *
    yunhe
 *  @return
 */
-(BaseTableView *)courseTable{
    if (!_courseTable) {
        _courseTable                  = [[BaseTableView alloc] initWithFrame:CGRectMake(0, CALENDARHEIGHT, ScreenWidth, ScreenHeihgt - NavHe-CALENDARHEIGHT - 49) style:UITableViewStylePlain withHeadRefresh:NO andFoodRefresh:NO];
        _courseTable.dataSource       = self;
        _courseTable.delegate         = self;
        _courseTable.separatorStyle   = UITableViewCellSeparatorStyleNone;
        _courseTable.backgroundColor  = [UIColor whiteColor];
        _courseTable.isNeedWhiteBackground = YES;
    }
    return _courseTable;
}
//TODO:FSCalendar delegate
/**
 *  按钮选择事件
 *
 *  @param calendar
 *  @param date
 */
- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date{
    _selectDate = date;
    [self getDataForTable:date];
}
//TODO:FSCalendar datasource
- (NSString *)calendar:(FSCalendar *)calendar subtitleForDate:(NSDate *)date{
    if ([date fs_isEqualToDateForDay:[NSDate date]]) {
        return @"今天";
    }
   return @"";
}
- (BOOL)calendar:(FSCalendar *)calendar hasEventForDate:(NSDate *)date{
    return YES;
}
/**
 *  日期下方image
 *
 *  @param calendar
 *  @param date
 *
 *  @return
 */
-(UIImage *)calendar:(FSCalendar *)calendar imageForDate:(NSDate *)date{
    return [self getDateImage:date];
}

- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar{
    [self getDataForCalendar:calendar.currentPage];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//TODO:tabledelegate datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _courseClassArray.count;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 65;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = UIView.new;
    [view setFrame:CGRectMake(0, 0, ScreenWidth, 10)];
    [view setBackgroundColor:[UIColor clearColor]];
    return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *indentifity = @"courseCell";
    CourseCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifity];
    if (!cell) {
        cell = [[CourseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifity];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    [cell setCellData:[_courseClassArray objectAtIndex:indexPath.row]];
    [cell setFirstImg:indexPath.row];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DetailCourseRecordVC *detailCourserecordVC = [[DetailCourseRecordVC alloc] init];
    detailCourserecordVC.myClassRecord = [_courseClassArray objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:detailCourserecordVC animated:YES];
}

//TODO:action
-(void)comeToToday{
    [self.courseCalendar setCurrentPage:[NSDate date] animated:YES];
    [self.courseCalendar selectDate:[NSDate date] scrollToDate:YES];
    [self getDataForTable:[NSDate date]];
    _selectDate = [NSDate date];
}
-(void)getAllCourseAction{
    AllCourseClassVC *allCourseClassVC = [[AllCourseClassVC alloc] init];
    [self.navigationController pushViewController:allCourseClassVC animated:YES];
}
//TODO:获取网络接口数据
- (void)getCourseRecordStartDate:(NSDate *)startDate endDate:(NSDate *)endDate{
    ClassCourseViewModel *classCourseViewModel = [[ClassCourseViewModel alloc] init];
    [classCourseViewModel setBlockWithReturnBlock:^(id returnValue) {
        _datesArray = [ClassCourseViewModel getLocalCourseRecourse:startDate endDate:endDate];
        [self.courseCalendar reloadData];
    } WithErrorBlock:nil WithFailureBlock:nil];
    [classCourseViewModel getCourseRecordByDates:startDate endDate:endDate];
}
- (void)getCourseRecord:(NSDate *)date{
    ClassCourseViewModel *classCourseViewModel = [[ClassCourseViewModel alloc] init];
    [classCourseViewModel setBlockWithReturnBlock:^(id returnValue) {
        _courseClassArray = [ClassCourseViewModel getLocalCourseRecord:date];
        [self.courseTable reloadData];
    } WithErrorBlock:nil WithFailureBlock:nil];
    [classCourseViewModel getCourseRecord:date];
}
//TODO:获取本地数据
- (void)getDataForCalendar:(NSDate *)currentDate{
    _datesArray = [ClassCourseViewModel getLocalCourseRecourse:[[currentDate fs_dateByAddingMonths:-1] fs_firstDayOfMonth] endDate:[[currentDate fs_dateByAddingMonths:+1] fs_lastDayOfMonth]];
    [self.courseCalendar reloadData];
    [self getCourseRecordStartDate:[[currentDate fs_dateByAddingMonths:-1] fs_firstDayOfMonth] endDate:[[currentDate fs_dateByAddingMonths:+1] fs_lastDayOfMonth]];
}
- (void)getDataForTable:(NSDate *)nowDate{
    _courseClassArray = [ClassCourseViewModel getLocalCourseRecord:nowDate];
    [self.courseTable reloadData];
    [self getCourseRecord:nowDate];
}
//TODO:辅助方法
/**
 *  获取日历对应图标
 *
 *  @param date
 *
 *  @return
 */
- (UIImage *)getDateImage:(NSDate *)date{
    NSPredicate *courseRecordInDates = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"cgcDate = '%@' ",[date fs_stringWithFormat:kDateFormatdate]]];
    NSArray *dataArray = [_datesArray filteredArrayUsingPredicate:courseRecordInDates];
    __block NSInteger returnFlag = 0;
    if (dataArray.count == 0) {
        return nil;
    }
    else{
        [dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            MyClassRecord *myCourseRecord = (MyClassRecord *)obj;
            NSInteger flag = [myCourseRecord.cgcStatus integerValue];
            if (flag == 1 || flag == 0) {
                //还没有开始上课
                returnFlag = 1;
            }else{
                if (returnFlag == 1) {
                    
                }else{
                    if ([myCourseRecord.crAccess integerValue] == 0) {
                        returnFlag = 2;//为评价
                    }else{
                        returnFlag = 3;//已完成
                    }
                }
            }
        }];
    }
    if (returnFlag == 1) {
        return [UIImage imageNamed:@"day_select_y"];
    }else if (returnFlag == 2){
        return [UIImage imageNamed:@"day_select_g"];
    }else if (returnFlag == 3){
        return [UIImage imageNamed:@"day_select_h"];
    }
    return nil;
}
- (void)nsnofiationAction:(NSNotification *)notification{
    [self getDataForCalendar:self.courseCalendar.currentPage];
    [self getDataForTable:_selectDate];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
